package com.qf.mybatis;

import com.qf.dao.StudentDao;
import com.qf.pojo.Student;
import com.qf.utils.MyBatisUtils;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 动态SQL
 * @author lixu
 */
public class MybatisDynamicSql {


    /**
     *  if
     */
    @Test
    public void testDynamicSqlIf(){
        StudentDao studentDao = MyBatisUtils.getMapper(StudentDao.class);

        //一次查询  缓存有数据吗？ 没有啊 查询DB吧
        List<Student> studentList = studentDao.findStudentByQuery(null,"男","英语");
        System.out.println("===第一次查询结束");
        //二次查询 缓存有数据吗？ 有啊  不查DB了
        List<Student> studentList2 = studentDao.findStudentByQuery(null,"男","英语");
        //List<Student> studentList = studentDao.findStudentByQuery("jack","男",null);
        System.out.println("===第二次查询结束");

        for (Student student : studentList) {
            System.out.println(student.getId());
        }
        MyBatisUtils.commit();
    }
    /**
     * < trim >
     */
    @Test
    public void testDynamicSqlTrim(){
        StudentDao studentDao = MyBatisUtils.getMapper(StudentDao.class);

        List<Student> studentList = studentDao.findStudentByQueryTrim("jack","男","英语");

        for (Student student : studentList) {
            System.out.println(student.getId());
        }
        MyBatisUtils.commit();
    }
    /**
     *  <foreach></foreach>
     */
    @Test
    public void testDynamicSqlForeach(){
        StudentDao studentDao = MyBatisUtils.getMapper(StudentDao.class);

        List<Student> studentList = new ArrayList<>();
        Student student = new Student();
        student.setId(4);
        student.setName("" + new Random().nextInt(1000));
        student.setSex("男");
        studentList.add(student);
        Student student1 = new Student();
        student1.setId(5);
        student1.setName("" + new Random().nextInt(1000));
        student1.setSex("男");
        studentList.add(student1);
        Student student2 = new Student();
        student2.setId(6);
        student2.setName("" + new Random().nextInt(1000));
        student2.setSex("男");
        studentList.add(student2);
        studentDao.insertBatch(studentList);

        MyBatisUtils.commit();
    }
}
